package com.chen.service.impl;

import cn.hutool.core.bean.BeanException;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chen.constant.ResultConstant;
import com.chen.context.BaseContext;
import com.chen.exception.BaseException;
import com.chen.exception.NotFoundUserError;
import com.chen.mapper.ContactGroupMapper;
import com.chen.mapper.UsersMapper;
import com.chen.pojo.dto.GroupPersonIdDto;
import com.chen.pojo.entity.ContactGroup;
import com.chen.pojo.entity.User;
import com.chen.pojo.vo.ContactGroupVo;
import com.chen.service.ContactGroupService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 陈子安
 * @since 2023-11-30
 */
@Service
@Slf4j
public class ContactGroupServiceImpl extends ServiceImpl<ContactGroupMapper, ContactGroup> implements ContactGroupService {

    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private ContactGroupMapper contactGroupMapper;


    @Override
    public List<ContactGroupVo> getContactGroupAll() {
        Long currentId = BaseContext.getCurrentId();
        User byId = usersMapper.selectById(currentId);
        List<ContactGroup> contactGroupAll = new ArrayList<>();

        // 管理员 查询所有组
        if (byId.getIsAdmin() == 1) {
            contactGroupAll = list();

        } else if (byId.getIsAdmin() == 0) {
            LambdaUpdateWrapper<ContactGroup> wrapper = new LambdaUpdateWrapper<>();
            // 普通用户 只能查询自己创建的组
            wrapper.eq(ContactGroup::getCreateId, currentId);
            contactGroupAll = list(wrapper);

        }
        return BeanUtil.copyToList(contactGroupAll, ContactGroupVo.class);
    }

    @Override
    public ContactGroupVo getContactGroupByGroupId(Integer groupId) {
        Long currentId = BaseContext.getCurrentId();
        User byId = usersMapper.selectById(currentId);

        ContactGroup findGroupById = getById(groupId);
        if (findGroupById == null) {
            throw new NotFoundUserError(ResultConstant.MSG_NOT_FOUND_GROUP);
        }

        ContactGroup resultContactGroup = new ContactGroup();
        // 管理员 直接获取即可
        if (byId.getIsAdmin() == 1) {
            resultContactGroup = findGroupById;
        }

        // 普通用户，只能查询自己创建的组
        else if (byId.getIsAdmin() == 0) {
            Long createId = findGroupById.getCreateId();
            if (!currentId.equals(createId)) {
                throw new NotFoundUserError(ResultConstant.MSG_NOT_FOUND_GROUP);
            }
            resultContactGroup = findGroupById;
        }

        return BeanUtil.copyProperties(resultContactGroup, ContactGroupVo.class);
    }

    @Override
    public void deleteById(Integer id) {
        Long currentId = BaseContext.getCurrentId();
        ContactGroup findGroupById = getById(id);
        if (findGroupById == null) {
            throw new NotFoundUserError(ResultConstant.MSG_NOT_FOUND_GROUP);
        }
        User byId = usersMapper.selectById(currentId);
        // 管理员
        Integer isAdmin = byId.getIsAdmin();
        if (isAdmin == 1) {
            // 管理员 直接删除
            boolean b = removeById(id);
            if (!b) {
                throw new BaseException(ResultConstant.MSG_UNKNOWN_ERROR);
            }
        } else if (isAdmin == 0) {
            // 普通用户
            Long createId = findGroupById.getCreateId();
            if (Objects.equals(currentId, createId)) {
                // 创建者可以删除
                boolean b = removeById(id);
                if (!b) {
                    throw new BaseException(ResultConstant.MSG_UNKNOWN_ERROR);
                }
            } else {
                throw new NotFoundUserError(ResultConstant.MSG_NOT_FOUND_GROUP);
            }
        }
        // 删除中间表中关联的数据
        contactGroupMapper.delPersonGroupByGroupId(id);
    }

    @Override
    public ContactGroupVo addContactGroup(ContactGroup contactGroup) {
        Long currentId = BaseContext.getCurrentId();
        contactGroup.setCreateId(currentId);
        boolean flag = save(contactGroup);
        if (!flag) {
            throw new BaseException(ResultConstant.MSG_UNKNOWN_ERROR);
        }
        ContactGroup byId = getById(contactGroup.getId());

        log.info("新添加的组信息为：{}", byId);
        return BeanUtil.copyProperties(byId, ContactGroupVo.class);
    }


    @Override
    public ContactGroupVo updateGroupByGroupId(ContactGroup contactGroup) {
        Integer id = contactGroup.getId();
        if (id == null) {
            throw new BeanException(ResultConstant.MSG_UNKNOWN_ERROR);
        }
        ContactGroup byId = getById(id);
        if (byId == null) {
            throw new NotFoundUserError(ResultConstant.MSG_NOT_FOUND_GROUP);
        }

        Long currentId = BaseContext.getCurrentId();
        User user = usersMapper.selectById(currentId);
        Integer isAdmin = user.getIsAdmin();
        if (isAdmin == 1) {
            // 当前用户为管理员， 可以修个任何组
            boolean b = updateById(contactGroup);
            if (!b) {
                System.out.println("ContactGroupServiceImpl.updateGroupByGroupId");
                throw new BeanException(ResultConstant.MSG_UNKNOWN_ERROR);
            }
        } else if (isAdmin == 0) {
            // 普通用户只能修改自己创建出来的组
            if (!byId.getCreateId().equals(currentId)) {
                System.out.println("ContactGroupServiceImpl.updateGroupByGroupId");
                throw new NotFoundUserError(ResultConstant.MSG_NOT_FOUND_GROUP);
            }
            boolean b = updateById(contactGroup);
            if (!b) {
                System.out.println("ContactGroupServiceImpl.updateGroupByGroupId");
                throw new BaseException(ResultConstant.MSG_UNKNOWN_ERROR);
            }
        }
        ContactGroup group = getById(id);
        return BeanUtil.copyProperties(group, ContactGroupVo.class);
    }

    @Override
    public List<GroupPersonIdDto> getContactGroupByPersonId(List<Integer> ids) {
        List<GroupPersonIdDto> contactGroupByPersonId = contactGroupMapper.findContactGroupByPersonId(ids);
        return contactGroupByPersonId;

    }
}
